
/*
 * LoginForm.java
 *
 * Created on 06.10.2011, 10:01:35
 */
package nl.fontys.sofa.odr.odrvpplugin.dialog;

import com.vp.plugin.ApplicationManager;
import com.vp.plugin.view.IDialog;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import nl.fontys.sofa.odr.odrvpplugin.common.UserSettings;
import nl.fontys.sofa.odr.odrvpplugin.common.VPStrings;
import nl.fontys.sofa.odr.odrvpplugin.common.ValueRepository;
import nl.fontys.sofa.odr.odrvpplugin.controller.ConfigurationActionController;
import nl.rug.search.odr.ws.connection.WebServiceRequestException;
import nl.rug.search.odr.ws.connection.AuthorizedWebServiceFacade;
import nl.rug.search.odr.ws.dto.DecisionStateDTO;
import nl.rug.search.odr.ws.dto.ProjectDTO;
import nl.rug.search.odr.ws.dto.ProjectOverviewDTO;
import nl.rug.search.odr.ws.dto.RelationshipTypeDTO;

/**
 *
 * @author Vadim Emrich
 */
public class SelectProjectPanel extends javax.swing.JPanel {

    private IDialog dialog;
    private long selectedProjectID = 01;
    private List<ProjectOverviewDTO> projects;
    private UserSettings userSettings;

    /** Creates new form LoginForm */
    public SelectProjectPanel() {
        userSettings = (UserSettings) ValueRepository.getInstance().getValue(VPStrings.USERSETTINGS);
        initComponents();

        getAllMyProjects();
    }

    public void setDialog(IDialog dialog) {
        this.dialog = dialog;
    }

    private void setErrorMessage(String message) {
        errorLabel.setText(message);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("all")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        bannerLabel = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        loadDecisionsButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        projectsComboBox = new javax.swing.JComboBox();
        projectsLabel = new javax.swing.JLabel();
        errorLabel = new javax.swing.JLabel();

        setAutoscrolls(true);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setMinimumSize(new java.awt.Dimension(600, 300));
        setPreferredSize(new java.awt.Dimension(600, 300));

        bannerLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        bannerLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/banner.png"))); // NOI18N
        bannerLabel.setAutoscrolls(true);

        jPanel1.setAutoscrolls(true);
        jPanel1.setLayout(new java.awt.GridBagLayout());

        loadDecisionsButton.setText("Load Decisions");
        loadDecisionsButton.setEnabled(false);
        loadDecisionsButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                loadDecisionsButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        jPanel1.add(loadDecisionsButton, gridBagConstraints);

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        jPanel1.add(cancelButton, gridBagConstraints);

        projectsComboBox.setEnabled(false);
        projectsComboBox.setMinimumSize(new java.awt.Dimension(100, 27));
        projectsComboBox.setPreferredSize(new java.awt.Dimension(100, 27));
        projectsComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                projectsComboBoxActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.ipadx = 200;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        jPanel1.add(projectsComboBox, gridBagConstraints);

        projectsLabel.setText("Projects:");
        projectsLabel.setEnabled(false);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.ipadx = 5;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        jPanel1.add(projectsLabel, gridBagConstraints);

        errorLabel.setForeground(new java.awt.Color(204, 51, 0));
        errorLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.ipadx = 200;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        jPanel1.add(errorLabel, gridBagConstraints);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(bannerLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE)
            .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(bannerLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 219, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void projectsComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_projectsComboBoxActionPerformed
        evt.getID(); //to avoid unused formal paramter
        String projectName = (String) projectsComboBox.getSelectedItem();
        for (ProjectOverviewDTO prj : projects) {
            if (prj.getName().equals(projectName)) {
                selectedProjectID = prj.getId();
            }
        }
    }//GEN-LAST:event_projectsComboBoxActionPerformed

    private void getAllMyProjects() {
        setErrorMessage("");
        try {
            String user = userSettings.getUsername();
            String password = userSettings.getEncryptedPassword();
            String url = userSettings.getUrl();

            AuthorizedWebServiceFacade facade = new AuthorizedWebServiceFacade(url, user, password);

            projects = facade.getProjectOverview();

            projectsComboBox.removeAllItems();
            if (projects.size() > 0) {
                for (ProjectOverviewDTO prj : projects) {
                    projectsComboBox.addItem(prj.getName());
                }
                projectsLabel.setEnabled(true);
                projectsComboBox.setEnabled(true);
                loadDecisionsButton.setEnabled(true);
                loadDecisionsButton.requestFocusInWindow();
                loadDecisionsButton.requestFocus();
            }

        } catch (IOException ex) {
            setErrorMessage(ex.getMessage());
            ConfigurationActionController confController = new ConfigurationActionController();
            confController.performAction(null);
            getAllMyProjects();
        } catch (WebServiceRequestException ex) {
            if (ex.isNotFoundStatus()) {
                setErrorMessage("Wrong URL");
            } else if (ex.isUnauthorizedStatus()) {
                setErrorMessage("Wrong Login");
            } else {
                setErrorMessage("Connection Error: " + ex.getResponseCode());
            }

            ConfigurationActionController confController = new ConfigurationActionController();
            confController.performAction(null);
            getAllMyProjects();
        }
    }

    private void loadDecisionsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadDecisionsButtonActionPerformed
        evt.getID(); //to avoid unused formal paramter
        setErrorMessage("");
        try {
            String user = userSettings.getUsername();
            String password = userSettings.getEncryptedPassword();
            String url = userSettings.getUrl();

            AuthorizedWebServiceFacade facade = new AuthorizedWebServiceFacade(url, user, password);

            ProjectDTO prj = facade.getProject(selectedProjectID);

            ValueRepository.getInstance().setValue(VPStrings.PROJECT, prj);

            /**
             * 1. Retrieve new DecisionStates and RelationshipTypes from the web service.
             * 2. Store them in the userSettings
             * 3. Marshall the UserSettings to the file
             */
            UserSettings userSettingsInstance = (UserSettings) ValueRepository.getInstance().getValue(VPStrings.USERSETTINGS);

            List<RelationshipTypeDTO> relationshipTypes = facade.getCommonRelationshipTypes();
            List<DecisionStateDTO> decisionStates = facade.getCommonDecisionStates();

            userSettingsInstance.setDecisionStates(decisionStates);
            userSettingsInstance.setRelationshipTypes(relationshipTypes);

            File userSettingsFile = new File(VPStrings.USERSETTINGSFILELOCATION);

            JAXBContext context = JAXBContext.newInstance(UserSettings.class);
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(userSettingsInstance, userSettingsFile);

            ApplicationManager.instance().getViewManager().showMessage("Project loaded!");


            if (dialog != null) {
                dialog.close();
            }
        } catch (IOException ex) {
            setErrorMessage(ex.getMessage());
        } catch (WebServiceRequestException ex) {
            if (ex.isNotFoundStatus()) {
                setErrorMessage("Wrong URL");
            } else if (ex.isUnauthorizedStatus()) {
                setErrorMessage("Wrong Login");
            } else {
                setErrorMessage("Connection Error: " + ex.getResponseCode());
            }
        } catch (JAXBException jaxbEx) {
            setErrorMessage("JAXB Exception: " + jaxbEx.getMessage());
        }
    }//GEN-LAST:event_loadDecisionsButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        evt.getID(); //to avoid unused formal paramter
        if (dialog != null) {
            dialog.close();
        }
    }//GEN-LAST:event_cancelButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel bannerLabel;
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel errorLabel;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton loadDecisionsButton;
    private javax.swing.JComboBox projectsComboBox;
    private javax.swing.JLabel projectsLabel;
    // End of variables declaration//GEN-END:variables
}
